package com.xuecheng.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LoginDto;
import com.xuecheng.commons.model.vo.LoginVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.JwtUtils;
import com.xuecheng.system.domain.User;
import com.xuecheng.web.exception.BusinessException;
import com.xuecheng.system.mappers.UserMapper;
import com.xuecheng.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired(required = false)
    private UserMapper userMapper;

    //用户登录
    public ResponseResult login(LoginDto dto) {

        String phone = dto.getUsername();
        String password = dto.getPassword();
        String utype = dto.getUtype();
        //1、非空判断
        if (ObjectUtil.isEmpty(phone) || ObjectUtil.isEmpty(password) || ObjectUtil.isEmpty(utype)) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }

        //2、根据手机号和utype查询用户
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone, phone);
        qw.eq(User::getUtype, utype);
        User user = this.getOne(qw);
        //3、判断用户是否存在
        if (user == null) {
            //3.1、用户不存在，抛出异常
            throw new BusinessException(ErrorCode.LOGINERROR);
        }

        //3.2、用户存在
        //4、对输入的密码加密，比较密码是否一致
        password= DigestUtil.md5Hex(password);
        if (!password.equals(user.getPassword())) {
            throw new BusinessException(ErrorCode.LOGINERROR);
        }

        //5、存入token中，设置超时时间
        Map map = new HashMap();
        map.put("userId", user.getId());
        map.put("companyId", user.getCompanyId());
        map.put("companyName", user.getCompanyName());
        String token = JwtUtils.createToken(map, 240);

        //6、构造返回值
        LoginVo loginVo = new LoginVo();
        loginVo.setAccess_token(token);
        loginVo.setUsername(user.getName());

        return ResponseResult.okResult(loginVo);
    }
}
